package com.tecklab.demo.easyrules;

import com.tecklab.demo.utils.LogConsolehUtils;
import org.jeasy.rules.annotation.Action;
import org.jeasy.rules.annotation.Condition;
import org.jeasy.rules.annotation.Fact;
import org.jeasy.rules.annotation.Rule;
import org.jeasy.rules.api.Facts;
import org.jeasy.rules.api.Rules;
import org.jeasy.rules.api.RulesEngine;
import org.jeasy.rules.core.DefaultRulesEngine;
import org.jeasy.rules.mvel.MVELRuleFactory;
import org.jeasy.rules.support.reader.YamlRuleDefinitionReader;
import org.mvel2.ParserContext;

import java.io.FileReader;

@Rule(name = "weather rule", description = "if it rains then take an umbrella")
public class DynamicYamlRuleTest {

    @Condition
    public boolean itRains(@Fact("rain") boolean rain) {
        return rain;
    }

    @Action
    public void takeAnUmbrella() {
        System.out.println("It rains, take an umbrella!");
    }

    public static void main(String[] args) throws Exception {
        // 关闭日志框架日志打印
        LogConsolehUtils.disable();

        // 定时任务 or jdk WatchService
        MVELRuleFactory ruleFactory = new MVELRuleFactory(new YamlRuleDefinitionReader());
        ParserContext context = new ParserContext();
        Rules yamlRules = ruleFactory.createRules(new FileReader(DynamicYamlRuleTest.class.getClassLoader().getResource("rules/rules.yml").getFile()));

        // define facts
        Facts facts = new Facts();
        facts.put("total", 380);

        // fire rules on known facts
        RulesEngine rulesEngine = new DefaultRulesEngine();
        rulesEngine.fire(yamlRules, facts);
    }
}